package com.neouton.crm.product.service.impl;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.product.entity.ProductInfoVO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.crm.product.mapper.ProductInfoMapper;
import com.neouton.crm.product.service.IProductInfoServer;
import com.neouton.crm.supplier.entity.SupplierVO;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import com.neouton.crm.dictionary.service.IDictionaryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;

/**
 * @Author gaolin
 * @Date 2022/8/30 16:13
 * @Version 1.0
 */
@Service
public class ProductInfoServiceImpl implements IProductInfoServer {

    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private IDictionaryService dictionaryService;

    @Resource
    private IApprovalService approvalService;

    @Resource
    FeginService feginService;

    @Value("${webSit.web}")
    private String webSitUrl;


    @Override
    public PageUtil<ProductInfoVO> queryProductsByPage(IPage page,ProductInfoVO entity) {
        return new PageUtil(productInfoMapper.queryProductsByPage(page, entity));
    }

    @Override
    @Transactional
    public Boolean saveOrUpdateProduct(ProductInfoVO entity,String token) {
        //判断数据是否已在审批中
        ProductInfoVO productInfoVO = productInfoMapper.querProductApprovalByProductId(entity.getProductId());
        if( productInfoVO!=null && productInfoVO.getApprovalStatus() !=null && productInfoVO.getApprovalStatus() == 0 ){
            return false;
        }
        //获取审批人
        List<SysUserEntity> users = dictionaryService.queryMenuUserIdsByCode("productInfolist");
        //获取人员信息
        SysUserEntity user = users.get(0);
        Integer businessId = startProductApproval(token,user);
        entity.setBusinessId(businessId);
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 4, entity.getReason(),
                "",user.getUserId(),"");
        entity.setApprovalId(approval.getApprovalId());
        if (entity.getProductId() != null) {
            entity.setLastUpdateBy(AuthUtils.getUserId());
            productInfoMapper.backProductInfoData(entity.getLastUpdateBy(),entity.getProductId());
            productInfoMapper.updateProductInfo(entity);
        } else {
            entity.setLastUpdateBy(AuthUtils.getUserId());
            entity.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
            productInfoMapper.saveProductInfo(entity);
        }


        if(AuthUtils.getUserId().equals(user.getUserId())){
            approval.setCreator(AuthUtils.getUserId());
            //当前人是下一审批人
            this.approveProductInfo(approval,token,false);
        }else {
            //发送邮件
            //获取审批人
            Integer userId = AuthUtils.getUserId();
//            String titel = "【系统通知】产品信息 - 流程单审批通知";
//            String msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                    "<div><p style='text-indent: 2em'>您好，您有一张新的产品信息审批需要处理：</p></div>"+
//                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请人："+AuthUtils.getUserName() +" / "+ AuthUtils.getUserAccount()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请原因："+(StringUtils.isEmpty(entity.getReason()) ? "无":entity.getReason()) +"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请时间："+DateUtils.getCurrentTime()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>产品品牌："+entity.getProductBrand()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>产品名称："+entity.getProductName()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>产品型号："+entity.getProductModel()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
            //调用通知接口
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(),
                    new Timestamp(System.currentTimeMillis()),userId, 0,4,user.getUserId(),token));
        }

        return true;
    }

    @Override
    public void exportProductInfo(HttpServletResponse response,ProductInfoVO productInfo,String state) throws Exception{

        List<ProductInfoVO> productList = productInfoMapper.queryAllProducts(productInfo);
        List<String> codes = new ArrayList<>();
        codes.add("productType");
        codes.add("productPriority");
        codes.add("productUnit");
        Map<String, List<DictionaryLookupItemVO>> stringListMap = dictionaryService.queryDictionaryLookupInfo(null, codes);
        for (int i = 0; i < productList.size(); i++) {
            ProductInfoVO productInfoVO = productList.get(i);
            productInfoVO.setProductId(i+1);
            if("一指禅".equals(state)){
                productInfoVO.setProductCostPrice(new BigDecimal(0));
            }
            //获取字典项封装字典项数据
            //优先级
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("productPriority") ){
                if(dictionaryLookupItemVO.getItemCode().equals(productInfoVO.getProductPriority()+"")){
                    productInfoVO.setProductPriorityStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
            //产品类型
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("productType") ){
                if(dictionaryLookupItemVO.getItemCode().equals(productInfoVO.getProductCategory()+"")){
                    productInfoVO.setProductCategoryStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
            //产品单位
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("productUnit") ){
                if(dictionaryLookupItemVO.getItemCode().equals(productInfoVO.getProductUnit()+"")){
                    productInfoVO.setProductUnitStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
        }

        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String productTemplatePath = String.valueOf(properties.get("report.productTemplate"));

        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(productTemplatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("productInfo",productList);
        ReportUtils.exportExcel(params,map,"产品列表",response);
    }

    /**
     * 分页查询
     *
     * @param productInfoVO
     * @return
     */
    public List<ProductInfoVO> queryAllProductsForPur(ProductInfoVO productInfoVO){
        return productInfoMapper.queryAllProductsForPur(productInfoVO);
    }

    /**
     * 查询可用状态供应商
     *
     * @return
     */
    public List<SupplierVO> querySuppliers(){
        return productInfoMapper.querySuppliers();
    }

    /**
     * 查询全部供应商
     *
     * @return
     */
    public List<SupplierVO> queryAllSuppliers(){
        return productInfoMapper.queryAllSuppliers();
    }


    /**
     * 审批通过
     * @param approval
     * @return
     */
    @Transactional
    public Boolean approveProductInfo(ApprovalVO approval,String token,Boolean sendEmail){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setBusinessId(approval.getBusinessId());
        workFlowFeginService.approvalProcessByBusinessId(activitiVO);
        //记录日志信息

        //发送邮件
        ResponseAPI<SysUserEntity> res = feginService.searchUserInfoByIds(approval.getCreator(),token);
        SysUserEntity user = res.getResult();
        //发送邮件
        String titel = "【系统通知】产品信息 - 流程单审批通过通知";
        List<ProductInfoVO> productInfoVOS = this.queryProductsByApprovalId(approval.getApprovalId());
        String msg;
        if(sendEmail){
            if("导入".equals(approval.getRemark())){
                msg =  "<div><p>" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                        "<div><p style='text-indent: 2em'>您好，您申请的产品信息已通过：</p></div>"+
                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>审批人："+AuthUtils.getUserName() +" / "+ AuthUtils.getUserAccount()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>审批意见："+(StringUtils.isEmpty(approval.getOpinion()) ? "无":approval.getOpinion())+"</p></div>"+
                        "<div><p style='text-indent: 2em'>审批时间："+DateUtils.getCurrentTime()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>申请数量："+productInfoVOS.size()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 产品库管理 - 产品列表 " +
                        "<a href='"+webSitUrl+"/?m=crm&p=productInfoPath&me=productInfoListPath'>进入</a></p></div>"+
                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            }else {
                msg =  "<div><p>" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                        "<div><p style='text-indent: 2em'>您好，您申请的产品信息已通过：</p></div>"+
                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>审批人："+AuthUtils.getUserName() +" / "+ AuthUtils.getUserAccount()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>审批意见："+approval.getOpinion()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>审批时间："+DateUtils.getCurrentTime()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>产品品牌："+productInfoVOS.get(0).getProductBrand()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>产品名称："+productInfoVOS.get(0).getProductName()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>产品型号："+productInfoVOS.get(0).getProductModel()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 产品库管理 - 产品列表 " +
                        "<a href='"+webSitUrl+"/?m=crm&p=productInfoPath&me=productInfoListPath'>进入</a></p></div>"+
                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            }
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
            //调用通知接口
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(),approval.getCreateDataTime(),
                    approval.getCreator(),1,4,0,token));
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",approval.getOpinion());
        }else {
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",approval.getOpinion());
        }


        //更新为启用状态
        productInfoMapper.updateProductStateByApprovalId(approval);
        return approvalService.approved(null,approval.getApprovalId());
    }

    /**
     * 审批驳回
     * @param approval
     * @return
     */
    @Transactional
    public Boolean rejectionProductInfo(ApprovalVO approval, String token){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setBusinessId(approval.getBusinessId());
        workFlowFeginService.approvalProcessByBusinessId(activitiVO);

        ResponseAPI<SysUserEntity> res = feginService.searchUserInfoByIds(approval.getCreator(),token);
        SysUserEntity user = res.getResult();
        //发送邮件
        String titel = "【系统通知】产品信息 - 流程单审批驳回通知";
        String msg;
        List<ProductInfoVO> productInfoVOS = this.queryProductsByApprovalId(approval.getApprovalId());
        if("导入".equals(approval.getRemark())){
            msg =  "<div><p>" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您申请的产品信息已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+AuthUtils.getUserName()+ " / " + AuthUtils.getUserAccount() + "</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+(StringUtils.isEmpty(approval.getOpinion()) ? "无":approval.getOpinion())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+ DateUtils.getCurrentTime() +"</p></div>"+
                    "<div><p style='text-indent: 2em'>申请数量："+productInfoVOS.size()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 产品库管理 - 产品列表 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=productInfoPath&me=productInfoListPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            this.deleteProductByApprovalId(approval.getApprovalId());
        }else {
            msg =  "<div><p>" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您申请的产品信息已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+AuthUtils.getUserName()+ " / " + AuthUtils.getUserAccount() + "</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+(StringUtils.isEmpty(approval.getOpinion()) ? "无":approval.getOpinion())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+ DateUtils.getCurrentTime() +"</p></div>"+
                    "<div><p style='text-indent: 2em'>产品品牌："+productInfoVOS.get(0).getProductBrand()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>产品名称："+productInfoVOS.get(0).getProductName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>产品型号："+productInfoVOS.get(0).getProductModel()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 产品库管理 - 产品列表 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=productInfoPath&me=productInfoListPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        }
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
        //调用通知接口
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(),
                approval.getCreateDataTime(), approval.getCreator(), 1,4,0,token));
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",approval.getOpinion());
        return approvalService.approvalRejection(null,approval.getApprovalId());
    }

    /**
     * 更具工作流ID获取审批信息
     * @param workId
     * @return
     */
    public List<ProductInfoVO>  querProductApprovalByWorkId(Integer workId){
        return productInfoMapper.querProductApprovalByWorkId(workId);
    }

    /**
     * 更具工作流ID获取产品列表
     * @param approvalId
     * @return
     */
    public Map<String,Object> queryTodoProductsByApprovalId(Integer approvalId){
        HashMap<String,Object> res = new HashMap<>();
        res.put("products",productInfoMapper.queryTodoProductsByApprovalId(approvalId));
        res.put("approval",approvalService.queryApprovalByAppID(approvalId));
        return res;
    }

    /**
     * 更具工作流ID获取产品列表
     * @param approvalId
     * @return
     */
    public Map<String,Object> queryProductApprovalRecordByApprovalId(Integer approvalId){
        HashMap<String,Object> res = new HashMap<>();
        //先查询历史，如历史为空则查询现有
        List<ProductInfoVO> productInfoVOS = productInfoMapper.queryHistoryProductsByApprovalId(approvalId);
        if(productInfoVOS.size()>=1){
            res.put("products",productInfoVOS);
        }else {
            res.put("products",productInfoMapper.queryTodoProductsByApprovalId(approvalId));
        }
        res.put("approval",approvalService.queryApprovalByAppID(approvalId));
        return res;
    }

    /**
     * 更具工作流ID获取产品列表
     * @param approvalId
     * @return
     */
    public List<ProductInfoVO> queryProductsByApprovalId(Integer approvalId){
        return productInfoMapper.queryTodoProductsByApprovalId(approvalId);
    }


    /**
     * 产品导入功能
     * @param file
     * @param supperId
     * @param reason
     * @return
     */
    @Transactional
    public String importProducts(MultipartFile file, Integer supperId,Integer isOneFinger, String reason , String token) throws Exception{
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        List<ProductInfoVO> productList = ReportUtils.importExcel(file.getInputStream(),ProductInfoVO.class, params);
        //校验数据是否为空
        if(productList.size()<=0){
            return "传入数据允许为空";
        }
        //封装集合数据，数据字典数据填充
        this.organizeImportProductData(productList);
        //校验非空字段
        String error = this.checkProductData(productList);
        if (!StringUtils.isBlank(error)){
             return error;
        }
        //获取审批人
        List<SysUserEntity> users = dictionaryService.queryMenuUserIdsByCode("productInfolist");
        //获取审批人人员信息
        ResponseAPI<SysUserEntity> res = feginService.searchUserInfoByIds(users.get(0).getUserId(),token);
        SysUserEntity user = res.getResult();
        //创建审批流
        Integer businessId = startProductApproval(token,user);
        //生成审批数据
        //生成日志信息
        //生成日志表信息
        if("null".equals(reason)){
            reason = null;
        }
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 4, reason,
                "",user.getUserId(),"导入");
        //存入产品数据
        productInfoMapper.insertProducts(productList,approval.getApprovalId(),supperId,isOneFinger);
        if(AuthUtils.getUserId().equals(user.getUserId())){
            approval.setCreator(AuthUtils.getUserId());
            //当前人是下一审批人
            this.approveProductInfo(approval,token,false);
        }else {
            //发送审批邮件
            //发送邮件
//        String titel = "【系统通知】产品信息 - 流程单审批通知";
//        String msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                "<div><p style='text-indent: 2em'>您好，您有一张新的产品信息审批需要处理：</p></div>"+
//                "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                "<div><p style='text-indent: 2em'>申请人："+AuthUtils.getUserName()+ " / " + AuthUtils.getUserAccount() + "</p></div>"+
//                "<div><p style='text-indent: 2em'>申请原因："+(StringUtils.isEmpty(reason) ? "无":reason)+"</p></div>"+
//                "<div><p style='text-indent: 2em'>申请时间："+DateUtils.getCurrentTime()+"</p></div>"+
//                "<div><p style='text-indent: 2em'>申请数量："+productList.size()+"</p></div>"+
//                "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
            //调用通知接口生成待办通知
            //获取申请人
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(),
                    new Timestamp(System.currentTimeMillis()), userId, 0,4,user.getUserId(),token));
        }
        return "导入成功";
    }

    /**
     * 整理导入数据
     */
    private void organizeImportProductData(List<ProductInfoVO> productList){
        List<String> codes = new ArrayList<>();
        codes.add("productType");
        codes.add("productPriority");
        codes.add("productUnit");
        Map<String, List<DictionaryLookupItemVO>> stringListMap = dictionaryService.queryDictionaryLookupInfo(
                null, codes);
        //封装所有数据
        for (int i = 0; i < productList.size(); i++) {
            ProductInfoVO productInfoVO = productList.get(i);
            //获取字典项封装字典项数据
            //优先级
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("productPriority") ){
                if(dictionaryLookupItemVO.getItemName().equals(productInfoVO.getProductPriorityStr())){
                    productInfoVO.setProductPriority(Integer.parseInt(dictionaryLookupItemVO.getItemCode()));
                    break;
                }
            }
            //产品类型
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("productType") ){
                if(dictionaryLookupItemVO.getItemName().equals(productInfoVO.getProductCategoryStr())){
                    productInfoVO.setProductCategory(Integer.parseInt(dictionaryLookupItemVO.getItemCode()));
                    break;
                }
            }
            //产品单位
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("productUnit") ){
                if(dictionaryLookupItemVO.getItemName().equals(productInfoVO.getProductUnitStr())){
                    productInfoVO.setProductUnit(Integer.parseInt(dictionaryLookupItemVO.getItemCode()));
                    break;
                }
            }
        }
    }

    /**
     * 总体校验导入产品问题
     * @param products
     * @return
     */
    private String checkProductData(List<ProductInfoVO> products){
        for (ProductInfoVO product:products){
            StringBuffer erroeHead = new StringBuffer();
            erroeHead.append("序号:"+products.indexOf(product)+1);
            erroeHead.append(";产品名称:"+product.getProductName()+";");
            erroeHead.append("存在以下问题，请处理后再进行导入操作!");
            StringBuffer errorBuffer = new StringBuffer();
            errorBuffer.append(this.checkProductCategory(product));
            errorBuffer.append(this.checkProductName(product));
            errorBuffer.append(this.checkProductBrand(product));
            errorBuffer.append(this.checkProductModel(product));
            errorBuffer.append(this.checkProductField(product));
            errorBuffer.append(this.checkProductPriority(product));
            errorBuffer.append(this.checkProductCostPrice(product));
            errorBuffer.append(this.checkProductSalesPrice(product));
            errorBuffer.append(this.checkProductFunction(product));
            errorBuffer.append(this.checkProductUnit(product));
            errorBuffer.append(this.checkRemark(product));
            errorBuffer.append(this.checkProductScene(product));
            if (errorBuffer.length()>0){
                return erroeHead.append(errorBuffer).toString();
            }
        }
        return "";
    }

    /**
     * 校验产品类别
     * @param product
     * @return
     */
    private String checkProductCategory(ProductInfoVO product){
        if(null == product.getProductCategory() && null !=  product.getProductCategoryStr()){
            return "请输入正确的产品类别；";
        }
        if(null == product.getProductCategory()){
            return "产品类别不能为空；";
        }
        return "";
    }

    /**
     * 校验产品名称
     * @param product
     * @return
     */
    private String checkProductName(ProductInfoVO product){
        if(StringUtils.isBlank(product.getProductName()) || StringUtils.isBlank(product.getProductName().trim())){
            return "产品名称不能为空；";
        }
        if(product.getProductName().length() > 30){
            return "产品名称不应超过 30 个字符；";
        }
        return "";
    }

    /**
     * 校验产品品牌
     * @param product
     * @return
     */
    private String checkProductBrand(ProductInfoVO product){
        if(StringUtils.isBlank(product.getProductBrand()) || StringUtils.isBlank(product.getProductBrand().trim())){
            return "产品品牌不能为空；";
        }
        if(product.getProductBrand().length()>10){
            return "产品品牌不应超过 10 个字符；";
        }
        return "";
    }

    /**
     * 校验产品型号
     * @param product
     * @return
     */
    private String checkProductModel(ProductInfoVO product){
        if(StringUtils.isBlank(product.getProductModel()) ||StringUtils.isBlank(product.getProductModel().trim()) ){
            return "产品型号不能为空；";
        }
        if(product.getProductModel().length()>20 ){
            return "产品型号不应超过 20 个字符；";
        }
        return "";
    }

    /**
     * 校验产品应领域
     * @param product
     * @return
     */
    private String checkProductField(ProductInfoVO product){
        if( product.getProductField() != null && product.getProductField().length() > 20){
            return "产品领域不应超过 20 个字符；";
        }
        return "";
    }

    /**
     * 校验应用场景
     * @param product
     * @return
     */
    private String checkProductScene(ProductInfoVO product){
        if(!StringUtils.isBlank(product.getProductScene())
                && product.getProductScene().length() > 100){
            return "客户场景不允许超过 100 个字符；";
        }
        return "";
    }

    /**
     * 校验备注
     * @param product
     * @return
     */
    private String checkRemark(ProductInfoVO product){
        if(!StringUtils.isBlank(product.getRemark())
                && product.getProductScene().length() > 100){
            return "备注不允许超过 100 个字符；";
        }
        return "";
    }



    /**
     * 校验产品单位
     * @param product
     * @return
     */
    private String checkProductUnit(ProductInfoVO product){
        if( null == product.getProductUnit() && null != product.getProductUnitStr()){
            return "请输入正确的产品单位；";
        }
        if( null == product.getProductUnit()){
            return "产品单位不能为空；";
        }
        return "";
    }

    /**
     * 校验产品优先级
     * @param product
     * @return
     */
    private String checkProductPriority(ProductInfoVO product){
        if( null == product.getProductPriority() && null != product.getProductPriorityStr()){
            return "请输入正确的优先级；";
        }
        if( null == product.getProductPriority()){
            return "优先级不能为空；";
        }
        return "";
    }

    /**
     * 校验产品成本价
     * @param product
     * @return
     */
    private String checkProductCostPrice(ProductInfoVO product){
        if( null == product.getProductCostPriceStr()){
            return "成本价不能为空；";
        }
        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        if(!pattern.matcher(product.getProductCostPriceStr()).matches()){
            return "请输入正确的成本价；";
        }
        return "";
    }

    /**
     * 校验产品销售价
     * @param product
     * @return
     */
    private String checkProductSalesPrice(ProductInfoVO product){
        if( null == product.getProductSalesPriceStr()){
            return "销售价不能为空；";
        }
        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        if(!pattern.matcher(product.getProductSalesPriceStr()).matches()){
            return "请输入正确的成本价；";
        }
        return "";
    }


    /**
     * 校验产品销售价
     * @param product
     * @return
     */
    private String checkProductFunction(ProductInfoVO product){
//        if( StringUtils.isBlank(product.getProductFunction()) || StringUtils.isBlank(product.getProductFunction().trim())){
//            return "产品功能不能为空；";
//        }
        if( product.getProductFunction() !=null && product.getProductFunction().length() > 100){
            return "产品功能不允许超过 100 个字符；";
        }
        return "";
    }

    /**
     * 开启审批流程
     * @param token
     * @param user
     * @return
     */
    private Integer startProductApproval(String token,SysUserEntity user){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("产品库审批流程");
        activitiVO.setProcessCode("product_approval");
        activitiVO.setVersion("1");
        activitiVO.setNextNodeParams("user");
        activitiVO.setNextNodeAssignee(user.getAccount());
        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startProcessByDesignCodeVersionCustomParams(activitiVO);
        return responseAPI.getResult().getBusinessId();
    }

    public void downProductTemplate(HttpServletResponse response) throws Exception{
        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String productTemplatePath = String.valueOf(properties.get("report.productTemplateDowen"));
        File file = new File(productTemplatePath);
        InputStream stream = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte buff[] = new byte[1024];
        int length = 0;

        while ((length = stream.read(buff)) > 0) {
            out.write(buff,0,length);
        }
        response.setContentType("application/x-download");
        String fileName = URLEncoder.encode("产品模板", "UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        stream.close();
        out.close();
        out.flush();
    }

    /**
     * 更新启用、禁用状态
     * @param productInfo
     * @return
     */
    public Boolean updateProductState(ProductInfoVO productInfo){
        return productInfoMapper.updateProductState(productInfo);
    }

    /**
     * 如审批驳回则删除导入产品
     * @return
     */
    public Boolean deleteProductByApprovalId(Integer approvalId){
        productInfoMapper.backProductInfoDataByApprovalId(approvalId);
        return productInfoMapper.deleteProductByApprovalId(approvalId);
    }

    /**
     * 分页查询待办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ProductInfoVO> queryApprovalProductByPage(IPage page, ProductInfoVO entity){
        //获取工作流待办
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<List<ActivitiVO>> workFlowVoResponseAPI = workFlowFeginService.getTasksByAuthorization(activitiVO);
        List<ActivitiVO> activitiVOS = workFlowVoResponseAPI.getResult();
        if( activitiVOS == null || activitiVOS.size() == 0 ){
            return new PageUtil(new PageDTO());
        }else{
            return new   PageUtil(productInfoMapper.queryApprovalProductByPage(page, entity,activitiVOS));
        }
    }

    /**
     * 分页查询已办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ProductInfoVO> queryApprovalProductDoneByPage(IPage page, ProductInfoVO entity){
        IPage<ProductInfoVO> iPage = productInfoMapper.queryApprovalProductDoneByPage(page, entity);
        return new PageUtil(iPage);
    }


    /**
     * 分页查询申请记录信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ProductInfoVO> queryApprovalProductRecordByPage(IPage page, ProductInfoVO entity,String token){
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"approvalRecord", token);
        IPage<ProductInfoVO> iPage = productInfoMapper.queryApprovalProductRecordByPage(page, entity,userList);
        return new PageUtil(iPage);
    }

    public List<SysUserEntity> queryUserList(Integer userId,String authCode, String token) {
        List<SysUserEntity> userList = new ArrayList<>();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode(authCode);
        boolean result = false;
        for (SysUserEntity user:authUserIList) {
            if (Objects.equals(user.getUserId(), userId)) {
                result = true;
            }
        }
        if (result) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        } else {
            SysUserEntity user = feginService.searchUserInfoByIds(userId,token).getResult();
            if (user.getIsLeader() == 1) {
                userList = feginService.recursiveQueryAllUserByLeaderId(userId, token).getResult();
            }
            userList.add(user);
        }
        return userList;
    }

}
